package ua.org.plast.mobileApp.news;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import ua.org.plast.mobileApp.R;
import ua.org.plast.mobileApp.news.tools.Article;
import ua.org.plast.mobileApp.utils.ImageUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Virus1908
 * Date: 18.11.13
 * Time: 20:56
 */
public class NewsListAdapter extends ArrayAdapter<Article> {
    private SimpleDateFormat mDateFormat;
    private SimpleDateFormat mTimeFormat;

    public NewsListAdapter(Context context, Article[] objects) {
        super(context, -1, objects);
        mDateFormat = new SimpleDateFormat("dd.MM.yyyy");
        mTimeFormat = new SimpleDateFormat("HH:mm");
    }

    public NewsListAdapter(Context context, List<Article> objects) {
        super(context, -1, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder currentView;
        if (convertView == null) {
            convertView = View.inflate(parent.getContext(), R.layout.news_item, null);
            currentView = new ViewHolder();
            currentView.icon = (ImageView) convertView.findViewById(R.id.icon);
            currentView.title = (TextView) convertView.findViewById(R.id.title);
            currentView.date = (TextView) convertView.findViewById(R.id.date);
            currentView.time = (TextView) convertView.findViewById(R.id.time);
            currentView.content = (WebView) convertView.findViewById(R.id.content);
            convertView.setTag(currentView);
        } else {
            currentView = (ViewHolder) convertView.getTag();
        }
        Article item = getItem(position);
        Bitmap bitmap = ImageUtils.getBitmap(item.getImgLink());
        if (bitmap != null) {
            currentView.icon.setImageBitmap(bitmap);
        }
        currentView.title.setText(item.getTitle());
        currentView.date.setText(item.getPubDate());
        currentView.content.getSettings().setJavaScriptEnabled(true);
        String summary = "<body>" + item.getDescription() + "</body></html>";
        currentView.content.loadDataWithBaseURL(null, summary, "text/html", "UTF-8", null);

        return convertView;
    }

    private static class ViewHolder {
        ImageView icon;
        TextView title;
        WebView content;
        TextView date;
        TextView time;
    }
}
